import React, { JSX } from 'react';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import '@fontsource/open-sans';
import { FormControl, MenuItem, Select, TextField } from '@mui/material';
import { useAppDispatch } from '../../actions/hook';
import { createNewUser } from '../../actions/UserManagement';
import '@fontsource/open-sans';

interface CreateUserProps {
  open: boolean;
  onClose: () => void;
}

function CreateUser(props: CreateUserProps): JSX.Element {
  const { open, onClose } = props;

  const [name, setName] = React.useState<string>('');
  const [userName, setUserName] = React.useState<string>('');
  const [gender, setGender] = React.useState<string>('');
  const [authority, setAuthority] = React.useState<string>('user');

  const dispatch = useAppDispatch();

  const clear = () => {
    setName('');
    setUserName('');
    setGender('');
    setAuthority('');
  }

  const onCreateClicked = () => {
    dispatch(createNewUser({ name, userName, gender, authority }));
    onClose();
    clear();
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Create New User'
      operations={
        <NulCommonOperations
          onPositiveClicked={onCreateClicked}
          onNegativeClicked={onClose}
          positiveText='Create'
        />
      }
    >
      <NulFormItem hint='User Name' component={
        <TextField placeholder='User Name' fullWidth={true} size='small' value={userName} onChange={(event) => { setUserName(event.target.value); }} />
      } />
      <NulFormItem hint='Name' component={
        <TextField placeholder='Name' fullWidth={true} size='small' value={name} onChange={(event) => { setName(event.target.value); }} />
      } />
      <NulFormItem hint='Gender' component={
        <FormControl fullWidth size='small'>
          <Select
            labelId="type-select-label"
            id="type-select"
            value={gender}
            placeholder="Type"
            onChange={(event) => {
              if (event.target.value === 'male' || event.target.value === 'female')
                setGender(event.target.value);
            }}
          >
            <MenuItem value='male'>Male</MenuItem>
            <MenuItem value='female'>Female</MenuItem>
          </Select>
        </FormControl>
      } />
      <NulFormItem hint='Authority' component={
        <FormControl fullWidth size='small'>
          <Select
            labelId="type-select-label"
            id="type-select"
            value={authority}
            placeholder="Type"
            onChange={(event) => {
              if (event.target.value === 'user' || event.target.value === 'admin')
                setAuthority(event.target.value);
            }}
          >
            <MenuItem value='user'>User</MenuItem>
            <MenuItem value='admin'>Administrator</MenuItem>
          </Select>
        </FormControl>
      } />
    </NulDialog>
  );
}

export { CreateUser };